package com.stickerview.view;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.qozix.tileview.R;
import com.stickerview.core.sticker.IMGSticker;
import com.stickerview.core.sticker.IMGStickerAdjustHelper;
import com.stickerview.core.sticker.IMGStickerHelper;
import com.stickerview.core.sticker.IMGStickerMoveHelper;
import com.stickerview.core.sticker.IMGStickerPortrait;

import java.io.InputStream;


/**
 * Created by felix on 2017/12/12 下午4:26.
 */

public abstract class StickerView extends ViewGroup implements IMGSticker, View.OnClickListener{


    private static final String TAG = "IMGStickerView";

    private View mContentView;

    private float mScale = 1f;
    public boolean isLock = false ;


    // TODO
    private int mDownShowing = 0;

    private IMGStickerMoveHelper mMoveHelper;


    private IMGStickerHelper<StickerView> mStickerHelper;

    private ImageView mRemoveView, mAdjustView,mFlipView,mLockView,mAddView;

    private float mMaxScaleValue = MAX_SCALE_VALUE;
    private AssetManager assetManager ;
    private Paint PAINT,PAINT1;

    private Matrix mMatrix = new Matrix();

    private RectF mFrame = new RectF();

    private Rect mTempFrame = new Rect();

    private static final float MAX_SCALE_VALUE = 4f;

    private static final int ANCHOR_SIZE = 48;

    private static final int ANCHOR_SIZE_HALF = ANCHOR_SIZE >> 1;

    private static int timeout=400;//双击间四百毫秒延时
    private int clickCount = 0;//记录连续点击次数
    private Handler handler;

    public int getmFilp() {
        return mFilp;
    }

    public void setmFilp(int mFilp) {
        this.mFilp = mFilp;
    }

    public int mFilp;

    private IMGStickerAdjustHelper imgStickerAdjustHelper;

    private static final float STROKE_WIDTH = 3f;

    {
        PAINT = new Paint(Paint.ANTI_ALIAS_FLAG);
        PAINT.setColor(Color.WHITE);
        PAINT.setStyle(Paint.Style.STROKE);
        PAINT.setStrokeWidth(STROKE_WIDTH);
    }
    {
        PAINT1 = new Paint(Paint.ANTI_ALIAS_FLAG);
        PAINT1.setColor(Color.TRANSPARENT);
        PAINT1.setStyle(Paint.Style.STROKE);
        PAINT1.setStrokeWidth(STROKE_WIDTH);
    }

    public StickerView(Context context) {
        this(context, null, 0);
    }

    public StickerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        handler = new Handler();
        onInitialize(context);
    }

    public void onInitialize(Context context) {
        setBackgroundColor(Color.TRANSPARENT);
        assetManager=getContext().getAssets();
        mContentView = onCreateContentView(context);
        addView(mContentView, getContentLayoutParams());

        mRemoveView = new ImageView(context);
        mRemoveView.setScaleType(ImageView.ScaleType.FIT_XY);
        mRemoveView.setImageResource(R.mipmap.image_ic_delete);
        addView(mRemoveView, getAnchorLayoutParams());
        mRemoveView.setOnClickListener(this);


        mFlipView = new ImageView(context);
        mFlipView.setScaleType(ImageView.ScaleType.FIT_XY);
        mFlipView.setImageResource(R.mipmap.image_ic_flip);
        addView(mFlipView, getAnchorLayoutParams());
        mFlipView.setOnClickListener(this);

        mLockView = new ImageView(context);
        mLockView.setScaleType(ImageView.ScaleType.FIT_XY);
        mLockView.setImageResource(R.mipmap.image_ic_lock);
        addView(mLockView, getAnchorLayoutParams());
        mLockView.setOnClickListener(this);

        mAddView = new ImageView(context);
        mAddView.setScaleType(ImageView.ScaleType.FIT_XY);
        mAddView.setImageResource(R.mipmap.image_ic_copy);
        addView(mAddView, getAnchorLayoutParams());
        mAddView.setOnClickListener(this);


        mAdjustView = new ImageView(context);
        mAdjustView.setScaleType(ImageView.ScaleType.FIT_XY);
        mAdjustView.setImageResource(R.mipmap.image_ic_adjust);
        addView(mAdjustView, getAnchorLayoutParams());

        imgStickerAdjustHelper =  new IMGStickerAdjustHelper(this, mAdjustView);

        mStickerHelper = new IMGStickerHelper<>(this);
        mMoveHelper = new IMGStickerMoveHelper(this);

    }

    public abstract View onCreateContentView(Context context);

    @Override
    public float getScale() {
        return this.mScale;
    }



    @Override
    public void setScale(float scale) {
        this.mScale = scale;
        drowFrame(mScale);
    }
    public void setInitScale(float scale){
        this.mScale = scale;
    }
    public void setLastScale(){
        drowFrame(getScale());
    }
    public void drowFrame(float scale){



        mContentView.setScaleX(scale);
        mContentView.setScaleY(scale);

        int left = getLeft();
        int top = getTop();

       int pivotX = (left + getRight()) >> 1;
       int pivotY = (top + getBottom()) >> 1;

        mFrame.set(pivotX, pivotY, pivotX, pivotY);
        mFrame.inset(-(mContentView.getMeasuredWidth() >> 1), -(mContentView.getMeasuredHeight() >> 1));

        mMatrix.setScale(scale, scale, mFrame.centerX(), mFrame.centerY());
        mMatrix.mapRect(mFrame);

        mFrame.round(mTempFrame);


        layout(mTempFrame.left, mTempFrame.top, mTempFrame.right, mTempFrame.bottom);

    }

    /**
     * 此方法为手动缩放使用，限制大小
     * @param scale
     */
    @Override
    public void addScale(float scale) {
        float size = 0.4f;
        if(mContentView.getWidth()>600||mContentView.getHeight()>600){
            size = 0.2f;
        }
        if(scale<1&&mContentView.getScaleX()<size){
            return;
        }
        setScale(getScale() * scale);
    }

    /**
     * 此方法为地图缩放使用，不限制大小
     * @param scale
     */
    public void addScale1(float scale) {
        float size = 0.4f;
        if(mContentView.getWidth()>600||mContentView.getHeight()>600){
            size = 0.2f;
        }
        if(scale<0.95&&mContentView.getScaleX()<size){
            return;
        }
        setScale(getScale() * scale);

    }
    private LayoutParams getContentLayoutParams() {
        return new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
        );
    }

    private LayoutParams getAnchorLayoutParams() {
        return new LayoutParams(ANCHOR_SIZE, ANCHOR_SIZE);
    }

    @Override
    public void draw(Canvas canvas) {
        if (!isLock) {
            canvas.drawRect(ANCHOR_SIZE_HALF, ANCHOR_SIZE_HALF,
                    getWidth() - ANCHOR_SIZE_HALF,
                    getHeight() - ANCHOR_SIZE_HALF, PAINT);
        }
        super.draw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                child.measure(widthMeasureSpec, heightMeasureSpec);

                maxWidth = Math.round(Math.max(maxWidth, child.getMeasuredWidth() * child.getScaleX()));
                maxHeight = Math.round(Math.max(maxHeight, child.getMeasuredHeight() * child.getScaleY()));

                childState = combineMeasuredStates(childState, child.getMeasuredState());
            }
        }

        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        int count = getChildCount();
        if (count == 0) {
            return;
        }

        mFrame.set(left, top, right, bottom);


        mRemoveView.layout(0, 0, mRemoveView.getMeasuredWidth(), mRemoveView.getMeasuredHeight());
        mAdjustView.layout(
                right - left - mAdjustView.getMeasuredWidth(),
                bottom - top - mAdjustView.getMeasuredHeight(),
                right - left, bottom - top
        );
        mFlipView.layout(
                right - left - mFlipView.getMeasuredWidth(),
                0,
                right - left, mFlipView.getMeasuredHeight()
        );

        mLockView.layout(
                0,
                bottom - top - mLockView.getMeasuredHeight(),
                mLockView.getMeasuredWidth(),bottom - top
        );

        mAddView.layout(
                (right - left)/2-mLockView.getMeasuredWidth()/2,
                bottom - top - mLockView.getMeasuredHeight(),
                (right - left)/2+mLockView.getMeasuredWidth()/2,bottom - top
        );


        int centerX = (right - left) >> 1, centerY = (bottom - top) >> 1;
        int hw = mContentView.getMeasuredWidth() >> 1;
        int hh = mContentView.getMeasuredHeight() >> 1;

        mContentView.layout(centerX - hw, centerY - hh, centerX + hw, centerY + hh);
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return isShowing() && super.drawChild(canvas, child, drawingTime);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int count = ev.getPointerCount();
        if(count>1){
            return false;
        }
        if (isLock && ev.getAction() == MotionEvent.ACTION_DOWN) {
            mDownShowing = 0;
            return true;
        }
        return  super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int count = event.getPointerCount();
        if(count>1){
            return false;
        }
        if(isLock){
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    clickCount++;
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(clickCount==2){
                               unlock();
                            }
                            handler.removeCallbacksAndMessages(null);
                            clickCount = 0;//计数清零
                        }
                    },timeout);
                    break;
            }
        }else{
            boolean handled = mMoveHelper.onTouch(this, event);
            return handled | super.onTouchEvent(event);
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v == mRemoveView) {
            onRemove();
        }else if(v==mLockView){
            lock();
        }else if(v==mFlipView){
           changeFlip();
        }else if(v==mAddView){
            copy();
        }
    }

    /**
     * 复制当前
     */
    public void copy(){
        mMoveHelper.mCallback.onCopy(this);
    }
    public void changeFlip(){
        ImageView imageView = (ImageView) mContentView;
        String path = (String) imageView.getTag(R.id.tag_first);
        int filp = (int) imageView.getTag(R.id.tag_second);
        if(path.length()>1){
            try {
                InputStream in=assetManager.open(path);
                Bitmap bmp=BitmapFactory.decodeStream(in);
                if(filp==0) {
                    Bitmap newb = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
                    Canvas cv = new Canvas(newb);
                    Matrix m = new Matrix();
                    m.postScale(-1, 1); //镜像水平翻转
                    Bitmap new2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
                    cv.drawBitmap(new2, new Rect(0, 0, new2.getWidth(), new2.getHeight()),new Rect(0, 0, bmp.getWidth(), bmp.getHeight()), null);
                    imageView.setImageBitmap(newb);
                    imageView.setTag(R.id.tag_second,1);
                    mFilp = 1 ;
                }else {
                    imageView.setImageBitmap(bmp);
                    imageView.setTag(R.id.tag_second,0);
                    mFilp = 0 ;
                }

            } catch (Exception e) {
            }
        }
    }

    public void lock(){
        if(!isLock){
            isLock = true ;
            mRemoveView.setVisibility(INVISIBLE);
            mLockView.setVisibility(INVISIBLE);
            mFlipView.setVisibility(INVISIBLE);
            mAdjustView.setVisibility(INVISIBLE);
            mAddView.setVisibility(INVISIBLE);
            imgStickerAdjustHelper.lock();
            mMoveHelper.lock();
            //invalidate();
            //drowFrame(mScale);
        }
    }
    public void unlock(){
        if(isLock){
            isLock = false ;
            mRemoveView.setVisibility(VISIBLE);
            mLockView.setVisibility(VISIBLE);
            mFlipView.setVisibility(VISIBLE);
            mAdjustView.setVisibility(VISIBLE);
            mAddView.setVisibility(VISIBLE);
            imgStickerAdjustHelper.unlock();
            mMoveHelper.unlock();
            //invalidate();
            //drowFrame(mScale);
        }
    }

    public void onRemove() {
        mStickerHelper.remove();
    }

    public void onContentTap() {
        if(isLock){
            unlock();
        }
    }

    @Override
    public boolean show() {
        return mStickerHelper.show();
    }

    @Override
    public boolean remove() {
        return mStickerHelper.remove();
    }

    @Override
    public boolean dismiss() {
        return mStickerHelper.dismiss();
    }

    @Override
    public boolean isShowing() {
        return mStickerHelper.isShowing();
    }

    @Override
    public RectF getFrame() {
        return mStickerHelper.getFrame();
    }

    @Override
    public void onSticker(Canvas canvas) {
        canvas.translate(mContentView.getX(), mContentView.getY());
        mContentView.draw(canvas);
    }

    @Override
    public void registerCallback(Callback callback) {
        mStickerHelper.registerCallback(callback);
        mMoveHelper.registerCallback(callback);
        imgStickerAdjustHelper.registerCallback(callback);
    }

    @Override
    public void unregisterCallback(Callback callback) {
        mStickerHelper.unregisterCallback(callback);
        mMoveHelper.unregisterCallback(callback);
        imgStickerAdjustHelper.unregisterCallback(callback);
    }
}
